//
//  FirstVC.swift
//  BLEManagerSwiftDemo
//
//  Created by Qinsz on 2019/5/22.
//  Copyright © 2019年 Qinsz. All rights reserved.
//


import UIKit

let needMtk = false

class FirstVC: UIViewController,UITableViewDelegate,UITableViewDataSource,KCTSingleBLEShellDelegate,KCTSingleBLEShellSearchDelegate,KCTMTKShellDelegate {
    func mtkShell(scanPeripheral: CBPeripheral) {
        
    }
    

    @IBOutlet weak var versionLabel: UILabel!
    @IBOutlet weak var tableView: UITableView!
    
    var peripherals = Array<CBPeripheral>.init()
    
    private let shell = KCTSingleBLEShell.sharedInstance
    
    /// 通过注释，打开/关闭MTK模块
    private var mtkShell:KCTMTKShell? = KCTMTKShell.share
    private var mtkConnectionTimer:Timer?

    override func viewDidLoad() {
        super.viewDidLoad()
        self.becomeFirstResponder()
        if let infos = Bundle.main.infoDictionary,let version = infos["CFBundleShortVersionString"] as? String {
            versionLabel.text = "v" + version
            if let build = infos["CFBundleVersion"] as? String {
                versionLabel.text?.append(".\(build)")
            }
        }
        versionLabel.sizeToFit()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        shell.delegate = self
        shell.searchDelegate = self
        mtkShell?.delegate = self
    }
    
    @IBAction func clickNetWorkTest(_ sender: Any) {
        
        let testVC = NetWorkTestVC.init(nibName: "NetWorkTestVC", bundle: Bundle.main)
        self.navigationController?.pushViewController(testVC, animated: true)
    }
    
    
    @IBAction func clickSearch(_ sender: Any) {
        
        let doAction = UIAlertAction.init(title: "是", style: .default) {[weak self] (action) in
            self?.startScanWithFilter(filter: true)
        }
        let doNotAction = UIAlertAction.init(title: "否", style: .cancel) {[weak self] (action) in
            self?.startScanWithFilter(filter: false)
        }
        let controller = UIAlertController.init(title: "是否通过服务UUID进行过滤", message: nil, preferredStyle: .alert)
        controller.addAction(doNotAction)
        controller.addAction(doAction)
        self.present(controller, animated: true, completion: nil)
        
    }
    
    private func startScanWithFilter(filter:Bool){
        peripherals.removeAll()
        peripherals.append(contentsOf: shell.retrievePairedPeripherals())
        tableView.reloadData()
        shell.startScan(withServicesFilter: filter)
        if mtkShell?.shakedHands == false{
            // 容错处理: 已经握手时，调用mtk的搜索方法会导致无法发送消息，且无法重新握手（只有在设置中忽略设备后才能恢复正常）
            mtkShell?.startScan()
        }
    }
    
    @IBAction func clickJump(_ sender: Any) {
        let cmdVC = BLECmdVC.init(nibName: "BLECmdVC", bundle: Bundle.main)
        self.navigationController?.pushViewController(cmdVC, animated: true)
    }
    
    @IBAction func clickJumpMTK(_ sender: Any) {
//        let mtkVC = MTKRawCmdVC.init(nibName: "MTKRawCmdVC", bundle: Bundle.main)
//        self.navigationController?.pushViewController(mtkVC, animated: true)
        let vc = KCTMTKTaskSendVC.init(nibName: "KCTMTKTaskSendVC", bundle: Bundle.main)
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    @IBAction func clickStop(_ sender: Any) {

        shell.stopScan()
        mtkShell?.stopScan()
    }
    
    
    //MARK:- tableView代理
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return peripherals.count
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 80
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        var deviceCell : KCTDeviceCell
        if let cell = tableView.dequeueReusableCell(withIdentifier: "KCTDeviceCell") {
            deviceCell = cell as! KCTDeviceCell
        }else{
            deviceCell = Bundle.main.loadNibNamed("KCTDeviceCell", owner: self, options: nil)?.first! as! KCTDeviceCell
        }
        deviceCell.per = peripherals[indexPath.row]

        return deviceCell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let peripheral = peripherals[indexPath.row]
        shell.stopScan()
        SVProgressHUD.show(withStatus: "正在连接...")
        if let name = peripheral.name {
            if name.contains("SW330") {
                peripheral.type = .Wear
            }
        }
        if peripheral.type == .Wear {
            if ( mtkShell != nil){
                if let t = mtkConnectionTimer {
                    t.invalidate()
                }
                mtkConnectionTimer = Timer.init(timeInterval: 30.0, target: self, selector: #selector(mtkConnectionTimeout(timer:)), userInfo: nil, repeats: false)
                RunLoop.main.add(mtkConnectionTimer!, forMode: .default)
                if mtkShell?.tempPeripheral?.state == .connecting || mtkShell?.tempPeripheral?.state == .connected{
                    mtkShell?.cancelConnection()
                }
                DispatchQueue.main.asyncAfter(deadline: .now()+3, execute:
                {
                    self.mtkShell?.connect(peripheral: peripheral)
                })

            }else{
                SVProgressHUD.showInfo(withStatus: "没有初始化MTKShell")
            }
        }else if peripheral.type == .Bracelet || peripheral.type == .Android{
            var shakeHande = true
            mtkShell?.stopScan()
            if let dfu = peripheral.name?.contains("DfuTarg"), dfu == true {
                shakeHande = false
            }
            shell.connect(peripheral: peripherals[indexPath.row], withShakehands: shakeHande)
        }else{
            SVProgressHUD.showInfo(withStatus: "未知的设备类型")
        }
    }

    
    /// MTK连接超时
    @objc func mtkConnectionTimeout(timer:Timer) {
        IPrint("连接MTK设备超时了")
        // 防止超时后的连接成功的回调
        mtkShell?.cancelConnection()
        SVProgressHUD.showInfo(withStatus: "连接MTK设备超时了")
    }
    
    
    //MARK:- MTKShell代理
    func mtkShellShakedHands(shell: KCTMTKShell) {
        IPrint("FirstVC:MTK握手成功")
        mtkConnectionTimer?.invalidate()
        shell.stopScan()
        SVProgressHUD.showSuccess(withStatus: "MTK握手成功")
//        let vc = MTKRawCmdVC.init(nibName: "MTKRawCmdVC", bundle: Bundle.main)
//        self.navigationController?.pushViewController(vc, animated: true)
        let vc = KCTMTKTaskSendVC.init(nibName: "KCTMTKTaskSendVC", bundle: Bundle.main)
        self.navigationController?.pushViewController(vc, animated: true)
    }
    func mtkShell(shell: KCTMTKShell, receivedData data: Data) {
        IPrint("FirstVC:MTK收到数据:\(NSData.init(data: data))")
    }
    func mtkShell(shell: KCTMTKShell, changeState state: Int32) {
        IPrint("FirstVC:MTK蓝牙状态改变:\(state)")
    }
    func mtkShell(shell: KCTMTKShell, received cmd: String, message: NSObject?, error: KCTError?) {
        var des:Any?
        if let obj = message,let js =  obj.yy_modelToJSONObject(){
            des = js
        }else{
            des = message
        }
        IPrint("MTKRawCmdVC:MTK收到解析后的消息:\ncmd=\(cmd)\nerror=\(error?.description ?? "")\nmessage=\(des ?? "")")
    }
    
    //MARK:- KCTSingleBLEShellSearchDelegate
    func singleBLEShell(shell: KCTSingleBLEShell, didDiscover peripheral: CBPeripheral) {
        
        // 将发现的设备通过通知POST出去，需要的页面自行监听该通知获取搜索结果
        NotificationCenter.default.post(name: Notification_DiscoveredPeripheral, object: peripheral)
        
        if !peripherals.contains(peripheral) {
            peripherals.append(peripheral)
            tableView.reloadData()
        }
    }
    
    //MARK:- KCTSingleBLEShellDelegate
    
    func singleBLEShell(shell: KCTSingleBLEShell, didUpdateState state: CBManagerState) {
        
    }
    
    func singleBLEShell(shell: KCTSingleBLEShell, failedToConnect peripheral: CBPeripheral, error: KCTError) {
        
        IPrint("链接失败:\(error)")
        
        SVProgressHUD.showError(withStatus: "链接失败:\(error)")
        
        // 将断开连接的消息POST出去，需要的页面自行监听该通知进行处理
        NotificationCenter.default.post(name: Notification_DisconnectBLEDevice, object: peripheral, userInfo: ["error":error])
        
    }
    func singleBLEShell(shell: KCTSingleBLEShell, successToConnect peripheral: CBPeripheral, handShaked: Bool) {
        
        IPrint("链接成功")
        
        NotificationCenter.default.post(name: Notification_ConnectBLEDevice, object: peripheral)
        
        if handShaked == true {
            // 握手连接的情况下，才自动进入BLECmdVC
            SVProgressHUD.showSuccess(withStatus: "BLE握手成功")
            let vc = BLECmdVC.init(nibName: "BLECmdVC", bundle: Bundle.main)
            self.navigationController?.pushViewController(vc, animated: true)
        }else{
            // 未握手的连接
            SVProgressHUD.showSuccess(withStatus: "连接成功(未握手)")
        }
        
    }
    func singleBLEShell(shell: KCTSingleBLEShell, serviceCharacteristicReceivedRawData rawData: Data) {
        let data = NSData.init(data: rawData)
        IPrint("收到原始蓝牙数据:\(data)")
    }
    func singleBLEShell(shell: KCTSingleBLEShell, recievedActiveMsg msgModel: NSObject) {
        if let json = msgModel.yy_modelToJSONObject(){
            IPrint("收到设备主动发来的消息:\(json)")
        }else{
            IPrint("收到设备主动发来的消息:\(msgModel)")
        }
        
    }
    
    override var preferredStatusBarStyle: UIStatusBarStyle{
        
        if #available(iOS 13.0, *){
            // 为了在不含darkContent的xcode版本上运行
            if let style =  UIStatusBarStyle.init(rawValue: 3) {
                return style
            }else{
                return .default
            }
        }else{
            return .default
        }
    }
}
